<template>
  <!-- 头部搜索框 -->
  <el-form :model="queryForm" :inline="true">
    <el-form-item label="角色标识" >
      <el-input v-model="queryForm.roleLabel" />
    </el-form-item>
    <el-form-item label="角色名称">
      <el-input v-model="queryForm.roleName" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleQuery">搜索</el-button>
      <el-button @click="handleRest">重置</el-button>
    </el-form-item>
    <el-form-item style="margin-left: 125px">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" @click="handleRemove(0)">删除</el-button>
    </el-form-item>
  </el-form>
  <!-- 列表 -->
  <el-table :data="tableData" style="width: 98%" row-key="roleId" default-expand-all @selection-change="handleSelectionChange" height="600px">
    <el-table-column type="selection" width="55" />
    <el-table-column type="index" label="序号" width="55" />
    <el-table-column prop="roleId" label="角色ID" width="150" />
    <el-table-column prop="roleLabel" label="角色标识" width="150" />
    <el-table-column prop="roleName" label="角色名称" width="150" />
    <el-table-column prop="status" label="角色状态" width="150" >
      <template #default="{ row }">
        <span v-if="row.status=== 1">停用</span>
        <span v-else-if="row.status === 0">正常</span>
      </template>
    </el-table-column>
    <el-table-column prop="createUser" label="创建者" width="200" />
    <el-table-column prop="updateUser" label="更新者" width="200" />
    <el-table-column prop="createTime" label="创建日期" width="200" />
    <el-table-column prop="updateTime" label="更新日期" width="200" />
    <el-table-column prop="remark" label="备注" width="200" />
    <el-table-column label="操作" width="200">
      <template #default="scope">
        <!-- v-if和v-show区别 -->
        <el-button link type="success" size="small" @click="handleEdit(scope.row.roleId)">修改</el-button>
        <el-button link type="danger" size="small" @click="handleRemove(scope.row.roleId)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <div class="pagination_container">
    <el-pagination v-model:current-page="queryForm.pageNum" v-model:page-size="queryForm.pageSize"
                   :page-sizes="[10, 20, 30, 40, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                   @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>

  <!-- 新增和修改的弹窗 -->
  <el-dialog v-model="menuFormShow" :title="menuTitle" width="50%" :before-close="handleClose">
    <!-- 表单 -->
    <el-form :model="form" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="角色标签" prop="form.roleLabel">
            <el-input v-model="form.roleLabel" placeholder="请输入角色标签"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色名称" prop="form.roleName">
            <el-input v-model="form.roleName" placeholder="请输入角色名称"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="排序" prop="form.sort">
            <el-input-number :min="0" v-model="form.sort"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="form.status">
            <el-switch
                v-model="form.status"
                active-text="正常"
                inactive-text="停用"
                :active-value="0"
                :inactive-value="1"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="备注" prop="form.remark">
            <el-input v-model="form.remark" placeholder="请输入备注"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleSubmit">提交</el-button>
            </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {onMounted, ref} from "vue";
import request from "@/utils/request";
import {ElMessage, ElMessageBox} from "element-plus";

let total = ref(0);
let selectIds = ref([])

let menuFormShow = ref(false);
let menuTitle = ref("");

let queryForm = ref({
  roleLabel: undefined,
  roleName: undefined,
  pageNum: 1,
  pageSize: 10
})

let form = ref({
  roleId : undefined,
  roleLabel : undefined,
  roleName : undefined,
  sort : undefined,
  status : undefined,
  createUser : 'admin',
  updateUser : 'admin',
  remark : undefined
})

const tableData = ref([
])


onMounted(() => {
  getRoleList()
});
const getRoleList = () => {

  request.get(`/ums/role/list/page`)
      .then(response => {
        tableData.value =response.data.data.list;
        total.value = response.data.data.total;
      })
}

// 重置
const handleRest = () => {
  const params = {
    roleLabel: undefined,
    roleName: undefined,
    pageNum : queryForm.value.pageNum,
    pageSize : queryForm.value.pageSize
  }
  request.get(`/ums/role/list/page`, {params})
      .then(res => {
        if(res.data.code === 200) {
          // 获取数据
          tableData.value = res.data.data.list;
          total.value = res.data.data.total;
        }
      })
}
// 搜索
const handleQuery = () => {
  const params = {
    roleLabel: queryForm.value.roleLabel,
    roleName: queryForm.value.roleName,
    pageNum : queryForm.value.pageNum,
    pageSize : queryForm.value.pageSize
  }
  request.get(`/ums/role/list/page`, {params})
      .then(res => {
        if(res.data.code === 200) {
          // 获取数据
          tableData.value = res.data.data.list;
          total.value = res.data.data.total;
          // 清空搜索框
          // queryForm.value = {}
        }
      })
}

const handleSizeChange = (sizeNumber) => {
  const params = {
    roleLabel: queryForm.value.roleLabel,
    roleName: queryForm.value.roleName,
    pageNum : queryForm.value.pageNum,
    pageSize : sizeNumber
  }
  request.get(`/ums/role/list/page`, {params})
      .then(res => {
        if(res.data.code === 200) {
          // 获取数据
          tableData.value = res.data.data.list;
          total.value = res.data.data.total;
        }
      })
}
// 点击下一页，上一页
const handleCurrentChange = (pageNumber) => {
  const params = {
    roleLabel: queryForm.value.roleLabel,
    roleName: queryForm.value.roleName,
    pageNum : pageNumber,
    pageSize : queryForm.value.pageSize
  }
  request.get(`/ums/role/list/page`, {params})
      .then(res => {
        if(res.data.code === 200) {
          // 获取数据
          tableData.value = res.data.data.list;
          total.value = res.data.data.total;
        }
      })
}

// 取消提交
const handleCancel = () =>{
  menuFormShow.value = false;
  form.value = {}
}

// 提交表单,根据form.id值判断是新增还是修改【有id值】
const handleSubmit = () => {
  // 做数据校验
  if(form.value.roleId) {
    // 修改
    request.put(`/ums/role`, form.value)
        .then(res => {
          if(res.data.code === 200) {
            // 关闭窗口
            menuFormShow.value = false;
            // 刷新列表
            getRoleList();
            //清除回显数据
            form.value = {};
            // 弹窗提示新增成功
            ElMessage({
              message: '修改角色信息成功！',
              type: 'success',
            })
          }else{
            // 弹窗提示新增失败
            ElMessage({
              message: '修改角色信息失败！',
              type: 'error',
            })
          }
        })
  }else {
    // 新增，调用新增接口
    request.post(`/ums/role`,form.value)
        .then(res => {
          console.log("res=======>",res);
          if(res.data.code === 200) {
            // 关闭窗口
            menuFormShow.value = false;
            // 刷新列表
            getRoleList();
            // 弹窗提示新增成功
            ElMessage({
              message: '新增角色成功！',
              type: 'success',
            })
          }
        })
  }
}

// 新增按钮，弹出表单
const handleAdd = () => {
  menuFormShow.value = true;
  menuTitle.value = "新增角色";
}
// 修改按钮，根据id查询对应的数据，弹出表单，回显数据
const handleEdit = (id) => {
  // 先查询数据，再弹窗
  request.get(`/ums/role/byOne?roleId=${id}`)
      .then(res => {
        if(res.data.code === 200) {
          // 保障后端返回的字段名和前端字段名相同，可以一一赋值
          form.value = res.data.data;
          menuFormShow.value = true;
          menuTitle.value = "修改角色信息";
        }else {
          ElMessage({
            message: '数据查询失败！',
            type: 'error',
          })
        }
      })

}

// 多选变化
const handleSelectionChange = (selection) => {
  let ids = selection.map(item => item.id)
  selectIds.value = ids;
}

// 删除按钮，弹出是否要删除数据，确定就删除，取消就不删除
const handleRemove = (id) => {
  // 走删除接口
  let ids = undefined;
  if(id > 0) {
    ids = [id]
  }else {
    ids = selectIds.value;
  }
  // id其实是点击操作下的删除按钮时才会有数据
  ElMessageBox.confirm(
      `确定要删除{${ids}}数据吗?`,
      '删除角色',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(() => {
        request.delete(`/ums/role?ids=${ids}`)
            .then(res => {
              if(res.data.code === 200) {
                ElMessage({
                  message: '删除成功',
                  type: 'success',
                })
                // 刷新列表
                getRoleList();
              }
            })
      })
      .catch(() => {
      })
}

// 关闭弹窗
const handleClose = () => {
  menuFormShow.value = false;
  form.value = {}
}
</script>

<style scoped lang="scss">
.pagination_container {
  position: relative;
  height: 40px;
  margin-top: 15px;

}

.el-pagination {
  position: absolute;
  right: 110px;
}
</style>